#!/usr/bin/python3
# author:szw
# 2023年06月27日
# Email:1259577135@qq.com
# desc:

import time
import requests
import json
import os
import shutil
import re
from bs4 import BeautifulSoup
proxies={'http':'127.0.0.1:15732',
         'https':'127.0.0.1:15732'}
def get_page(key_word:str,after=None):

    headers = {
        "authority": "www.behance.net",
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "content-type": "application/json",
        "origin": "https://www.behance.net",
        "referer": "https://www.behance.net/search/images",
        "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.41",
        "x-bcp": "d814ff56-c667-441a-8845-e4c1957fffe7",
        "x-requested-with": "XMLHttpRequest"
    }
    cookies = {
        "bcp": "d814ff56-c667-441a-8845-e4c1957fffe7",
    }
    url = "https://www.behance.net/v3/graphql"

    data = {"query":"\n      query GetProjectSearchResults($query: query, $filter: SearchResultFilter, $first: Int!, $after: String) {\n        search(query: $query, type: PROJECT, filter: $filter, first: $first, after: $after) {\n          pageInfo {\n            hasNextPage\n            endCursor\n          }\n          nodes {\n            ... on Project {\n              __typename\n              ...projectSearchFields\n            }\n          }\n          metaContent {\n            totalEntityCount\n            toolCard {\n              cta {\n                text\n                url\n              }\n              description\n              links {\n                text\n                url\n                type\n              }\n              slug\n              title\n            }\n            schoolCard {\n              cta {\n                text\n                url\n              }\n              description\n              slug\n            }\n            csam {\n              isCSAMViolation\n              description\n              helpResource\n              reportingOption\n            }\n            followableTag {\n              isFollowing\n              tag {\n                id\n                title\n              }\n            }\n          }\n        }\n      }\n\n      \n  fragment projectSearchFields on Project {\n    id\n    colors {\n      r\n      g\n      b\n    }\n    isMatureReviewSubmitted\n    linkedAssetsCount\n    name\n    premium\n    isPrivate\n    publishedOn\n    isFounder\n    isFeatured\n    modifiedOn\n    canBeAddedToMoodboard\n    adminFlags {\n      mature_lock\n      privacy_lock\n      dmca_lock\n      flagged_lock\n      privacy_violation_lock\n      trademark_lock\n      spam_lock\n      eu_ip_lock\n    }\n    features {\n      featuredOn\n      url\n      name\n      ribbon {\n        image\n        image2x\n        image3x\n      }\n    }\n    slug\n    stats {\n      views {\n        all\n      }\n      appreciations {\n        all\n      }\n      comments {\n        all\n      }\n    }\n    url\n    fields {\n      label\n    }\n    linkedAssets {\n      ...sourceLinkFields\n    }\n    sourceFiles {\n      ...sourceFileWithCoverFields\n    }\n    matureAccess\n    hasMatureContent\n    owners {\n      ...OwnerFields\n      images {\n        size_50 {\n          url\n        }\n        size_100 {\n          url\n        }\n        size_115 {\n          url\n        }\n        size_138 {\n          url\n        }\n        size_230 {\n          url\n        }\n        size_276 {\n          url\n        }\n      }\n    }\n    covers {\n      size_original {\n        url\n      }\n      size_max_808 {\n        url\n      }\n      size_808 {\n        url\n      }\n      size_404 {\n        url\n      }\n      size_202 {\n        url\n      }\n      size_230 {\n        url\n      }\n      size_115 {\n        url\n      }\n      size_original_webp {\n        url\n      }\n      size_max_808_webp {\n        url\n      }\n      size_808_webp {\n        url\n      }\n      size_404_webp {\n        url\n      }\n      size_202_webp {\n        url\n      }\n      size_230_webp {\n        url\n      }\n      size_115_webp {\n        url\n      }\n    }\n  }\n\n  \n  fragment sourceFileWithCoverFields on SourceFile {\n    __typename\n    sourceFileId\n    projectId\n    userId\n    title\n    assetId\n    renditionUrl\n    mimeType\n    size\n    category\n    licenseType\n    unitAmount\n    currency\n    tier\n    hidden\n    extension\n    hasUserPurchased\n    description\n    cover {\n      coverUrl\n      coverX\n      coverY\n      coverScale\n    }\n  }\n\n  \n  fragment sourceLinkFields on LinkedAsset {\n    __typename\n    name\n    premium\n    url\n    category\n    licenseType\n  }\n\n  \n  fragment OwnerFields on User {\n    displayName\n    hasPremiumAccess\n    id\n    isFollowing\n    isProfileOwner\n    location\n    locationUrl\n    url\n    username\n    isMessageButtonVisible\n    availabilityInfo {\n      availabilityTimeline\n      isAvailableFullTime\n      isAvailableFreelance\n      hiringTimeline {\n        key\n        label\n      }\n    }\n    creatorPro {\n      isActive\n      initialSubscriptionDate\n    }\n  }\n\n\n    ",
            "variables":{
                "query":key_word,
                "filter":{},
                "first":48
            }
            }
    if after:
        data["variables"]["after"] = after

    data = json.dumps(data, separators=(',', ':'))
    response = requests.post(url,proxies=proxies, headers=headers, cookies=cookies, data=data)
    requests.session().close()
    requests.session().keep_alive = False
    if response.text:
        return response.json()

def get_content_detail(url):
    # url = 'https://www.behance.net/gallery/136862181/Porsche-988R-VISION'
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
        "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        "Accept-Encoding": "gzip, deflate, br",
        "Connection": "keep-alive",
        "Upgrade-Insecure-Requests": "1",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "cross-site",
        "TE": "trailers"
    }
    cookies = {
        "gki": "{%22feature_creative_cloud_search%22:false%2C%22feature_gql_profile_drafts_request%22:false%2C%22recs_project_search_loggedout%22:false%2C%22feature_hire_include_freelance_activity%22:false}",
        "OptanonAlertBoxClosed": "2023-06-21T06:51:15.418Z",
        "OptanonConsent": "groups=C0001%3A1%2CC0002%3A1%2CC0003%3A1%2CC0004%3A1",
        "AMCV_9E1005A551ED61CA0A490D45%40AdobeOrg": "870038026%7CMCMID%7C09968874126259841161079466337033196426%7CMCAID%7CNONE%7CMCOPTOUT-1688701632s%7CNONE%7CMCAAMLH-1689299232%7C11%7CMCAAMB-1689299232%7Cj8Odv6LonN4r3an7LhD3WZrU1bUpAkFkkiY1ncBR96t2PTI%7CMCCIDH%7C1746874283%7CvVersion%7C5.0.0",
        "_fbp": "fb.1.1687330277516.744444468",
        "g_state": "{\"i_p\":1689219149673,\"i_l\":3}",
        "recent_items": "1=conceptcar|concept%20car|car|%E6%B1%BD%E8%BD%A6%E5%A4%96%E5%9E%8B|%E6%B1%BD%E8%BD%A6%E8%AE%BE%E8%AE%A1",
        "dialog_dismissals": "following_tags_ftux_tooltip%3Bannouncement_36%3Bannouncement_37",
        "sign_up_prompt": "true",
        "bcp": "05a1cf89-a9ce-4f9d-82f1-938cddbd8439",
        "bcp_generated": "1688612688454",
        "gk_suid": "94465981",
        "originalReferrer": "",
        "AMCVS_9E1005A551ED61CA0A490D45%40AdobeOrg": "1",
        "s_cc": "true",
        "s_sq": "%5B%5BB%5D%5D",
        "s_ppv": "[%22www.behance.net/gallery/136862181/Porsche-988R-VISION%22%2C35%2C0%2C2688%2C1334%2C960%2C1920%2C1080%2C1%2C%22P%22]",
        "gpv": "behance.net:gallery",
        "ilo0": "true"
    }
    params = {
        "mt": "login"
    }
    for i in range(5):
        try:
            response = requests.get(url, headers=headers, proxies=proxies, cookies=cookies, params=params)
            return response.text
        except:
            time.sleep(5)
    print(id,'data not get ')
    return None
def parse_content_detail(content):
    soups =BeautifulSoup(content,'lxml')
    try:
        datas =soups.find('div',id ='project-modules').find_all('img')
        return datas
    except:
        return None

if __name__ == '__main__':
    print()
    # response=get_page(key_word='conceptcar',after='')
    # print(response['data']['search']['pageInfo']['endCursor'])
    # print(nodes := response['data']['search']['nodes'])
    # print(len(nodes))

    url = 'https://www.behance.net/gallery/192144879/UNIQLO'
    content = get_content_detail(url)
    print(parse_content_detail(content))
